from lib.dbobjects import Profiler

import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

STARTING_MONEY = 500;
RICH = 1000

def is_new(profiler):
    total_hands = 0
    for i in xrange(4):
        total_hands += profiler.hands_per_level[i]
    for i in xrange(1):
        total_hands += profiler.challenges[i]
    return total_hands < 1

## @details This class helps perform the things that are useful for all the pages
class BaseRequestHandler(webapp.RequestHandler):
    
    LEVEL1_CUTOFF = 1
    LEVEL2_CUTOFF = 300
    LEVEL3_CUTOFF = 550
    LEVEL4_CUTOFF = 600
    LEVEL1_NAME = "GUESS THE CARD"
    LEVEL2_NAME = "GET A HAND"
    LEVEL3_NAME = "FLOW DOWN THE RIVER"
    LEVEL4_NAME = "POKER ROULETTE"

    CHALLENGE_CUTOFF = 400
    CHALLENGE_NAME = "HOLD'EM CHALLENGE"
    
    def generate(self, template_name, template_values={}, links=[], games=[]):
        
        # For now, always empty the links and games
        links = []
        games = []
        # Links contain all the links we want to display at the bottom
        links.append([users.create_logout_url('/'), 'Logout'])
        welcome_message = None
        
        if users.is_current_user_admin():
            links.append(['/admin', 'Admin Page'])
        else:
            links.append(['/', 'Main Page'])
            if 'profiler' in template_values:
                profiler = template_values['profiler']
                money = profiler.money
                
                # Generate welcome message
                if money >= RICH:
                    welcome_message = "Wow " + profiler.nickname + ", you are RICH!"
                elif is_new(profiler):
                    welcome_message = "Feel free to choose the game and dive right in.  Good luck " \
                            + profiler.nickname + "!"
                elif profiler.money > 0:
                    welcome_message = "You need to earn " + str(RICH - profiler.money) \
                    + " to get to the next challenge level"
                # Busted
                else:
                    if profiler.times_busted > 0 and profiler.times_busted % 500 == 0:
                        welcome_message = "Your stubbornness paid off! You'll get a refill of 500 again!"
                    elif profiler.times_busted >= 20:
                        welcome_message = "Wow " + profiler.nickname + ", that's a lot of busting!"
                    else:
                        welcome_message = profiler.nickname + ", you have lost all of your money. " + \
                        "It is time to learn from your mistakes!"
                        
                # Generate games
                for i in xrange(4):
                    level = str(i + 1)
                    cutoff = getattr(self, "LEVEL" + level + "_CUTOFF")
                    if money >= cutoff:
                        games.append(['/level' + level, getattr(self, 
                                "LEVEL" + level + "_NAME")])
                if money >= self.CHALLENGE_CUTOFF:
                    games.append(['/challenge', self.CHALLENGE_NAME])
                if money == 0:
                    links.append(['/refill', 'Start Over'])
        
        values = {
            'user': users.get_current_user(),
            'application_name': 'Poker with Igor',
            'links': links,
            'welcome_message': welcome_message,
            'games': games,
        }
        values.update(template_values)
        directory = os.path.dirname(__file__)
        path = os.path.join(directory, os.path.join('htmls', template_name))
        self.response.out.write(template.render(path, values))

    def display(self, html_page, user):
        # Get the profiler object for the current user
        profilers_query = Profiler.all().filter("user =", user).order('-modified')
        profiler = profilers_query.get()
        if profiler is None:
            self.generate(html_page)
        else:
            template_values = {'profiler': profiler}
            self.generate(html_page, template_values)